﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EPiAbstractions.Common.Queries;
using EPiServer.Common;
using EPiServer.Common.Comments;
using EPiServer.Common.Queries;
using JoelAbrahamsson.Web.ExtensionMethods;

namespace JoelAbrahamsson.Web.Common
{
    public class SameIpEntryValidator : ICommentValidator
    {
        private IQueryHandlerFacade _queryHandlerFacade;

        public SameIpEntryValidator(IQueryHandlerFacade queryHandlerFacade)
        {
            _queryHandlerFacade = queryHandlerFacade;
        }

        public bool Validate(HttpContextBase httpContext, Comment comment, IAuthor author, ModelStateDictionary modelState)
        {
            CommentQuery query = new CommentQuery();
            query.Created = new DateTimeCriterion();
            query.Created.Value = DateTime.Now.Subtract(new TimeSpan(0, 0, 0, 30));
            query.Created.Operator = ComparisonOperator.GreaterThan;

            int totalItems;
            CommentCollection comments = _queryHandlerFacade.GetQueryResult<IComment, CommentCollection>(query, TimeSpan.Zero, 1, int.MaxValue - 1, out totalItems);

            bool valid = comments.Count(c => c is Comment && ((Comment)c).GetAuthorIP() == comment.GetAuthorIP()) == 0;

            if(!valid)
                modelState.AddModelError("AuthorIP", "Another comment was posted from your IP address less than 30 seconds ago. Please wait a few seconds and try again.");

            return valid;
        }
    }
}
